import {post} from "@/utils/http.js";
import {desDecrypt, genDesKey, rsaPubEncrypt} from "@/utils/EncryptUtils.js";
import useAccountStore from "@/store/modules/AccountStore.js";
import {elMessageTip} from "@/utils/MessageTipUtils.js";
import {resolvePromise_data, resolvePromise_status} from "@/utils/ReturnUtils.js";
import request from "@/utils/request.js";

export const saveAddressAPI = (info) => {
    return post(
        '/address/save',
        {
            account: rsaPubEncrypt(useAccountStore().account),
            userId: useAccountStore().user.id,
            id: info.id ? info.id : null,
            name: rsaPubEncrypt(info.name),
            phone: rsaPubEncrypt(info.tel),
            province: rsaPubEncrypt(info.province),
            city: rsaPubEncrypt(info.city),
            county: rsaPubEncrypt(info.county),
            address: rsaPubEncrypt(info.addressDetail),
            idDefault: info.isDefault,
        }
    ).then(
        res => {
            elMessageTip(res)
            return resolvePromise_status(res)
        }
    )
}

export const updateAddressAPI = (address) => {
    return post(
        '/address/save',
        {
            account: rsaPubEncrypt(useAccountStore().account),
            userId: useAccountStore().user.id,
            id: address.id ? address.id : null,
            name: rsaPubEncrypt(address.name),
            phone: rsaPubEncrypt(address.phone),
            province: rsaPubEncrypt(address.province),
            city: rsaPubEncrypt(address.city),
            county: rsaPubEncrypt(address.county),
            address: rsaPubEncrypt(address.address),
            idDefault: address.idDefault,
        }
    ).then(
        res => {
            elMessageTip(res)
            return resolvePromise_status(res)
        }
    )
}

export const getAddressAPI = () => {
    const desKey = genDesKey()
    return request.get(
        '/address/all',
        {
            params: {
                account: rsaPubEncrypt(useAccountStore().account),
                desKey: rsaPubEncrypt(desKey),
                userId: useAccountStore().user.id,
            }
        }
    ).then(
        res => {
            res = desDecrypt(res, desKey)
            // elMessageTip(res)
            return resolvePromise_data(res)
        }
    )
}

export const delAddressAPI = (address) => {
    return post(
        '/address/del',
        {
            account: rsaPubEncrypt(useAccountStore().account),
            userId: useAccountStore().user.id,
            id: address.id ? address.id : null
        }
    ).then(
        res => {
            elMessageTip(res)
            return resolvePromise_status(res)
        }
    )
}